<template>
  <div class="app-container">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
      </div>
      
      <el-form label-width="80px">
        <el-form-item label="标题">
          <div class="audit-field-content" v-html="auditArticleData.title"></div>
        </el-form-item>
        <el-form-item label="副标题1" v-if="auditArticleData.littleTitle1">
          <div class="audit-field-content" v-html="auditArticleData.littleTitle1"></div>
        </el-form-item>
        <el-form-item label="副标题2" v-if="auditArticleData.littleTitle2">
          <div class="audit-field-content" v-html="auditArticleData.littleTitle2"></div>
        </el-form-item>
        <el-form-item label="文章来源">
          <div class="audit-field-content">{{ auditArticleData.articleOrigin }}</div>
        </el-form-item>
        <el-form-item label="栏目名称">
          <div class="audit-field-content">
            {{ (columnOptions.find(col => col.id === auditArticleData.columnId) || {}).name || '' }}
          </div>
        </el-form-item>
        <el-form-item label="责任编辑">
          <div class="audit-field-content">{{ auditArticleData.author }}</div>
        </el-form-item>
        <el-form-item label="内容">
          <div v-html="processedContent" class="audit-content"></div>
        </el-form-item>
         <!-- 封面 - 只有媒体聚焦栏目才显示 -->
         <el-form-item label="封面" v-if="isAuditArticleMediaFocus">
           <div class="audit-image-container" v-if="auditArticleData.coverPath">
             <image-preview 
               :src="auditArticleData.coverPath" 
               :width="200" 
               :height="150"
             />
           </div>
           <div class="audit-field-content" v-else>无封面图片</div>
         </el-form-item>
         <el-form-item label="审批表">
           <div class="audit-image-container" v-if="auditArticleData.appval">
             <image-preview 
               :src="auditArticleData.appval" 
               :width="200" 
               :height="150"
             />
           </div>
           <div class="audit-field-content" v-else>无审批表图片</div>
         </el-form-item>
      </el-form>
      
      <!-- 按钮区域 -->
      <div class="form-buttons">
        <el-button type="primary" @click="confirmAudit" :loading="auditLoading">确认审核</el-button>
        <el-button type="danger" @click="handleReject" :loading="rejectLoading">驳回</el-button>
        <!-- <el-button @click="goBack">返回</el-button> -->
      </div>
  </div>
</template>

<script>
import { getUncheck } from "@/api/uncheck/uncheck";
import { listConlumn, listConlumnListByRole } from "@/api/conlumn/conlumn";
import { auditArticle, updateToArticle, delArticleByAuditId } from "@/api/uncheck/uncheck";
import ImagePreview from "@/components/ImagePreview";

export default {
  name: "UncheckAudit",
  dicts: ['check'],
  components: {
    ImagePreview
  },
  data() {
    return {
      // 页面标题
      title: '文章审核',
      // 当前审核的文章数据
      auditArticleData: {},
      // 栏目选项
      columnOptions: [],
      // 加载状态
      auditLoading: false,
      rejectLoading: false,
      // 用户权限
      canAudit: false
    };
  },
  computed: {
    // 判断当前审核的文章是否为媒体聚焦栏目
    isAuditArticleMediaFocus() {
      if (!this.auditArticleData.columnId || !this.columnOptions.length) {
        return false;
      }
      const selectedColumn = this.columnOptions.find(col => col.id === this.auditArticleData.columnId);
      return selectedColumn && selectedColumn.name === '媒体聚焦';
    },
    
    // 处理内容中的图片，限制宽度为200px并保持比例
    processedContent() {
      if (!this.auditArticleData.content) {
        return '';
      }
      
      // 创建临时DOM元素来解析HTML
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = this.auditArticleData.content;
      
      // 查找所有img元素并修改其属性
      const images = tempDiv.querySelectorAll('img');
      images.forEach(img => {
        // 获取原始宽度和高度
        const originalWidth = img.getAttribute('width') || img.naturalWidth || 200;
        const originalHeight = img.getAttribute('height') || img.naturalHeight || 150;
        
        // 计算新的高度以保持比例
        const newWidth = 200;
        const aspectRatio = parseFloat(originalHeight) / parseFloat(originalWidth);
        const newHeight = Math.round(newWidth * aspectRatio);
        
        // 设置新的尺寸属性
        img.setAttribute('width', newWidth);
        img.setAttribute('height', newHeight);
        
        // 添加样式确保图片按比例显示
        img.style.width = newWidth + 'px';
        img.style.height = newHeight + 'px';
        img.style.maxWidth = '100%';
        img.style.height = 'auto';
        img.style.objectFit = 'contain';
      });
      
      return tempDiv.innerHTML;
    }
  },
  created() {
    this.initPage();
  },
  watch: {
    // 监听路由变化，只在必要时重新初始化页面
    '$route'(to, from) {
      // 只有当路由路径真正改变且目标路径是审核页面时才重新初始化
      if (to.path !== from.path && to.path === '/uncheck/audit') {
        // 检查是否有文章ID参数
        const { id } = to.query;
        if (id && id !== this.$route.query.id) {
          this.initPage();
        }
      }
    }
  },
  methods: {
    // 初始化页面
    async initPage() {
      await this.getColumnList();
      await this.loadUserInfo();
      
      // 获取路由参数
      const { id } = this.$route.query;
      
      if (id) {
        await this.loadArticleData(id);
      } else {
        this.$modal.msgError('缺少文章ID参数');
        this.goBack();
      }
    },

    // 加载用户信息
    loadUserInfo() {
      this.canAudit = this.$store.getters.roles.includes('admin') || this.$store.getters.roles.includes('city_admin');
    },

    // 加载文章数据
    async loadArticleData(id) {
      try {
        const response = await getUncheck(id);
        this.auditArticleData = response.data;
      } catch (error) {
        this.$modal.msgError('加载文章数据失败');
        this.goBack();
      }
    },

    // 加载栏目列表
    async getColumnList() {
      try {
        const response = await listConlumnListByRole();
        this.columnOptions = response.rows;
      } catch (error) {
        this.$modal.msgError('加载栏目列表失败');
      }
    },

    // 确认审核
    async confirmAudit() {
      this.auditLoading = true;
      try {
        // 复制一份数据，避免直接修改弹窗数据
        const form = {...this.auditArticleData};
        form.state = '1';
        // 自动设置办结日期为当前时间
        const now = new Date();
        form.pubdate = this.formatDate(now);
        // 先更新uncheck表的状态
        await updateToArticle(form);
        // 再插入到article表中
        await auditArticle(form);
        this.$modal.msgSuccess("审核成功");
        this.goBack();
      } catch (error) {
        this.$modal.msgError("审核失败，请重试");
        console.error(error);
      } finally {
        this.auditLoading = false;
      }
    },

    // 驳回文章
    async handleReject() {
      try {
        const { value } = await this.$prompt('请输入驳回理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/, // 输入内容不能为空
          inputErrorMessage: '驳回理由不能为空'
        });

        this.rejectLoading = true;
        
        // 获取当前行的数据
        const response = await getUncheck(this.auditArticleData.articleId);
        const form = response.data;

        // 更新备注为用户输入的驳回理由
        form.remark = value;
        form.state = "2";

        // 提交更新
        await updateToArticle(form);
        this.$modal.msgSuccess("驳回成功");
        this.goBack();
      } catch (error) {
        if (error !== 'cancel') {
          this.$modal.msgError('驳回失败');
          console.error(error);
        }
      } finally {
        this.rejectLoading = false;
      }
    },


    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 返回上一页
    goBack() {
      // 检查是否有历史记录可以返回
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        // 如果没有历史记录，跳转到文章列表页面
        this.$router.push('/uncheck/uncheck');
      }
    }
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.form-buttons {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

.form-buttons .el-button {
  margin: 0 10px;
  min-width: 100px;
}

.audit-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-all;
  border: 1px solid #e4e7ed;
  line-height: 1.6;
}

/* 内容区域滚动条样式 */
.audit-content::-webkit-scrollbar {
  width: 8px;
}

.audit-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.audit-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.audit-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 审核字段内容样式 */
.audit-field-content {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  min-height: 32px;
  word-break: break-all;
}

/* 审核图片容器样式 */
.audit-image-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 8px 12px;
  max-width: 100%;
}

/* 内容区域中的图片样式 */
.audit-content img {
  max-width: 200px !important;
  height: auto !important;
  width: auto !important;
  display: block;
  margin: 10px auto;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  object-fit: contain;
}

/* 确保图片在内容区域中正确显示 */
.audit-content {
  /* 重置一些可能影响图片显示的样式 */
  font-size: 14px;
}

.audit-content p {
  margin: 10px 0;
  line-height: 1.6;
}

.audit-content * {
  max-width: 100%;
}
</style>
